package com.zx.config.File;

import com.zx.model.user.User;
import com.zx.util.CookieUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunkai
 * @date 2022/8/15 0015 21:46
 * @mood zhou xun
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {


    static List<String> exeUrlList = new ArrayList<>();

    {
        exeUrlList.add("/user/login");
        exeUrlList.add("/comment/query");
        exeUrlList.add("/category/queryType");
        exeUrlList.add("/goods/recommend/goods");
        exeUrlList.add("/goods/query/list");
        exeUrlList.add("/goods/detail");
        exeUrlList.add("/goods/specification");
        exeUrlList.add("/goods/sort");
        exeUrlList.add("/goods/good/shop");
        exeUrlList.add("/");
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        User user = CookieUtil.queryCookie(request);
        if (user != null) {
            return true;
        }
        // Ant方式路径匹配 /**  ？  _
        String requestURI = request.getRequestURI();
        PathMatcher matcher = new AntPathMatcher();
        for (String ignoredUrl : exeUrlList) {
            if(matcher.match(ignoredUrl,requestURI)){
                return  true;
            }
        }

        response.setContentType("text/html;charset=utf-8");
        request.getRequestDispatcher("/WEB-INF/jsp/login.html").forward(request, response);
        return false;
    }
}
